<template>
  <div v-if="showList" class="equip-wrap-common">
    <px-form ref="formRef" class="custom-form-ui equip-form" :model="form" label-position="right" label-width="120px">
      <px-row :gutter="16">
        <px-col :span="6">
          <px-form-item label="设备名称" prop="eqpIdOrName">
            <px-input v-model="form.eqpIdOrName" clearable @blur="form.eqpIdOrName = $event.target.value.trim()" @keyup.enter="getList">
              <template #suffix>
                <px-icon class="pointer" @click="getList"><Search /></px-icon>
              </template>
            </px-input>
          </px-form-item>
        </px-col>
        <px-col :span="6">
          <px-form-item label="科室" prop="className">
            <px-select v-model="form.className" placeholder="请选择科室" filterable @change="classChanged">
              <px-option v-for="item in classNameList" :key="item.code" :label="item.name" :value="item.code" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="6">
          <px-form-item label="规则类型" prop="ruleTypeCode">
            <px-select v-model="form.ruleTypeCode" placeholder="请选择规则类型" clearable filterable>
              <px-option v-for="item in ruleTypeList" :key="item.code" :label="item.name" :value="item.code" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="6">
          <px-button type="primary" @click="getList">查询</px-button>
          <px-button @click="handleReset">重置</px-button>
        </px-col>
      </px-row>
    </px-form>
    <px-button v-has="'SYSTEM_BASE_RULE_ADD_RULE_STATUS'" type="primary" @click="handleAddRule">新增规则</px-button>
    <px-button v-has="'SYSTEM_BASE_RULE_DOWNLOAD'" type="primary" plain @click="handleDownload">下载模板</px-button>
    <px-upload
      v-has="'SYSTEM_BASE_RULE_IMPORT'"
      class="inline-block ml-[16px]"
      action="#"
      :http-request="handleImport"
      :show-file-list="false"
      accept=".xlsx, xls"
    >
      <px-button type="primary" plain>批量导入</px-button>
    </px-upload>

    <px-table :data="tableData" class="mt-[8px]" size="small" height="calc(100vh - 380px)" border>
      <px-table-column label="序号" width="100" align="center" fixed="left">
        <template #default="{ $index }">
          {{ $index + 1 + (paginationInfo.pageNum - 1) * paginationInfo.pageSize }}
        </template>
      </px-table-column>
      <px-table-column fixed prop="ruleTypeName" label="规则类型" show-overflow-tooltip />
      <px-table-column fixed prop="classNameDesc" label="科室" show-overflow-tooltip />
      <px-table-column fixed prop="eqpName" label="设备名称" show-overflow-tooltip />
      <px-table-column fixed prop="eqpId" label="设备编码" show-overflow-tooltip />
      <px-table-column width="160" prop="runStatusPoint" label="运行状态点位" show-overflow-tooltip />
      <px-table-column width="160" prop="runStatusFormula" label="运行状态规则" show-overflow-tooltip />
      <px-table-column width="160" prop="awaitStatusPoint" label="待机状态点位" show-overflow-tooltip />
      <px-table-column width="160" prop="awaitStatusFormula" label="待机状态规则" show-overflow-tooltip />
      <px-table-column width="160" prop="offlineStatusPoint" label="离线状态点位" show-overflow-tooltip />
      <px-table-column width="160" prop="offlineStatusFormula" label="离线状态规则" show-overflow-tooltip />
      <px-table-column width="160" prop="diseaseStatusPoint" label="带病状态点位" show-overflow-tooltip />
      <px-table-column width="160" prop="diseaseStatusFormula" label="带病状态规则" show-overflow-tooltip />
      <px-table-column width="160" prop="faultStatusPoint" label="故障状态点位" show-overflow-tooltip />
      <px-table-column width="160" prop="faultStatusFormula" label="故障状态规则" show-overflow-tooltip />
      <px-table-column width="160" prop="updateName" label="更新人" show-overflow-tooltip />
      <px-table-column width="160" prop="updateTime" label="更新时间" show-overflow-tooltip />
      <px-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="scope">
          <px-tooltip content="详情" placement="top">
            <px-button v-has="'SYSTEM_BASE_RULE_VIEW_RULE_STATUS'" link type="primary" icon="Tickets" @click="handleDetail(scope.row)" />
          </px-tooltip>
          <px-tooltip content="编辑" placement="top">
            <px-button v-has="'SYSTEM_BASE_RULE_EDIT_RULE_STATUS'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'SYSTEM_BASE_RULE_DELETE_RULE_STATUS'" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <pagination
      v-show="paginationInfo.total > 0"
      v-model:page="paginationInfo.pageNum"
      v-model:limit="paginationInfo.pageSize"
      :total="paginationInfo.total"
      @pagination="getList"
    />
  </div>
  <Teleport v-else to="#status-edit">
    <AddOrEdit :ruleId="ruleId" :type="type" @close="handleClose" />
  </Teleport>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from "vue";
import { PxMessageBox, PxMessage } from "px-ui";

import { getListForRuleType } from "@/api/system/runningStatusSetting/ruleDesc";
import type { IRuleSettingItem } from "@/api/system/runningStatusSetting/ruleSetting";
import { getListForSetting, deleteRuleForSetting, importRules } from "@/api/system/runningStatusSetting/ruleSetting";

import AddOrEdit from "./AddOrEdit.vue";
import type { IEmitsTypeForSettingList, PageType } from "../../type";

const classNameList = JSON.parse(localStorage.getItem("classList"));

const emits = defineEmits<IEmitsTypeForSettingList>();

const { proxy }: any = getCurrentInstance();
const form = ref({
  eqpIdOrName: "",
  className: "",
  ruleTypeCode: ""
});
const tableData = ref<IRuleSettingItem[]>([]);
const ruleTypeList = ref([]);
const paginationInfo = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
});
const type = ref<PageType>("add");
const ruleId = ref(null);
const showList = ref(true);
const formRef = ref(null);

if (classNameList.length === 1) {
  form.value.className = classNameList[0].code;
}

const handleClose = () => {
  showList.value = true;
  emits("toggle", true);
  getList();
};

const handleAddRule = () => {
  showList.value = false;
  ruleId.value = null;
  type.value = "add";
  emits("toggle", false);
};

const handleDetail = row => {
  showList.value = false;
  ruleId.value = row.id;
  type.value = "detail";
  emits("toggle", false);
};

const handleEdit = row => {
  showList.value = false;
  ruleId.value = row.id;
  type.value = "edit";
  emits("toggle", false);
};

const handleDelete = row => {
  PxMessageBox.confirm(`是否删除该设备运行状态规则说明？`, "提示", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    await deleteRuleForSetting(row.id);
    PxMessage.success("删除成功");
    getList();
  });
};
const handleDownload = () => {
  proxy.download("get", "/digitaltwins/api/v1/equipmentStatusRule/templateDownLoad", {}, "设备运行规则模板.xlsx");
};
const handleImport = async (options: { file: File }) => {
  try {
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    await importRules(formData);
    PxMessage.success("批量导入成功");
    getList();
  } catch (error) {
    console.log(error);
  }
};

const handleReset = () => {
  formRef.value?.resetFields();
  getList();
  getTypeList();
};

const classChanged = () => {
  form.value.ruleTypeCode = "";
  getTypeList();
};

const getTypeList = async () => {
  const params = {
    className: form.value.className
  };
  const data = await getListForRuleType(params);
  ruleTypeList.value = data.map(item => ({
    code: item.ruleTypeCode,
    name: item.ruleTypeName
  }));
};
const getList = async () => {
  const params = {
    pageSize: paginationInfo.value.pageSize,
    pageNum: paginationInfo.value.pageNum,
    ...form.value
  };
  const res = await getListForSetting(params);
  paginationInfo.value.total = res.total;
  tableData.value = res.data;
};

getList();
getTypeList();
</script>

<style lang="scss" scoped>
@import url("../../scss/table-list.scss");
</style>
